package com.easy.util;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.codec.Base64;


import java.util.Map;
import java.util.UUID;


public class CaptchaUtil {
    private static final ExpiryMap expiryMap=new ExpiryMap();
    private static final long EXPIRY_TIME=1000*60*8;


    //获取验证码
    public static Map getCaptcha(){
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = cn.hutool.captcha.CaptchaUtil.createLineCaptcha(200, 100, 4, 10);
        //图片
        lineCaptcha.getImageBytes();
        String imgbase64= Base64.encode(lineCaptcha.getImageBytes());
        System.out.println(imgbase64);
        //验证码中的编号
        String code = lineCaptcha.getCode();
        System.out.println(code);
        String key= UUID.randomUUID().toString();
        Map map=Map.of("key",key,"base","data:image/png;base64,"+imgbase64);



        expiryMap.put(key,code,EXPIRY_TIME);
        return map;
    }

    public static void main(String[] args)  {

        ExpiryMap expiryMap=new ExpiryMap();
        expiryMap.put("1","1");
        expiryMap.put("2","2",5000);
        try {
            Thread.sleep(7000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println(expiryMap.get("1"));
        System.out.println(expiryMap.get("2"));
    }
    //验证码校验
    public static boolean checkCaptcha(String key,String code){
        String captchaCode = (String) expiryMap.get(key);
        return code.equalsIgnoreCase(captchaCode);
    }
}
